package token

import (
	"fmt"

	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/types"
	tokentypes "hundsun.com/hsl/hschain/contract/native/token/types"
	ecom "hundsun.com/hsl/hschain/executor/common"
	protosrpc "hundsun.com/hsl/hschain/protos/rpc"
	"hundsun.com/hsl/hschain/store/extend/account"
)

// Query 查询部分，需要在worker里面启动一个mqlient
func (nt *nativeToken) Query(ctx *ecom.ExecContent, funcName string, param []byte) (proto.Message, error) {
	switch funcName {
	case tokentypes.QueryBalanceMethod:
		return nt.queryBalance(ctx, param)
	case tokentypes.QueryFrozenMethod:
		return nt.queryFrozen(ctx, param)
	default:
		return nil, fmt.Errorf("%s not implemented", funcName)
	}
}

func (nt *nativeToken) queryFrozen(ctx *ecom.ExecContent, param []byte) (proto.Message, error) {
	return nil, nil
}

func (nt *nativeToken) queryBalance(ctx *ecom.ExecContent, param []byte) (proto.Message, error) {
	if len(param) == 0 {
		return nil, types.ErrInvalidParam
	}
	bp := &protosrpc.GetBalanceParam{}
	err := proto.Unmarshal(param, bp)
	if err != nil {
		return nil, err
	}
	acce := account.NewAccountDB(ctx)
	acc, err := acce.GetAccount(bp.Address)
	if err != nil {
		return nil, err
	}
	return acc, nil
}
